import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
    // 用户ID
    const userId = ref(null)
    // 从本地存储恢复用户ID
    const initUserSession = () => {
        const storedUserId = localStorage.getItem('user_id')
        if (storedUserId) {
            userId.value = parseInt(storedUserId)
        }
    }
    // 设置用户ID
    const setUserId = (id) => {
        userId.value = id
        localStorage.setItem('user_id', id.toString())
    }
    // 清除用户会话
    const clearUserSession = () => {
        userId.value = null
        localStorage.removeItem('user_id')
    }
    // 计算属性判断用户是否登录
    const isLoggedIn = computed(() => {
        return userId.value!== null
    })
    // 初始化用户会话
    initUserSession()
    return {
        userId,
        isLoggedIn,
        setUserId,
        clearUserSession,
        initUserSession
    }
})